<template>
  <div>
    <a-alert type="info" show-icon style="margin-bottom: 18px">
      <template #message>
        可用于APP消息推送、站内信消息推送及报警(业务)通知推送。<a
          href="https://doc.21ds.cn/detail?doc=4731341806141859/4824489426116080"
          target="_blank"
          rel="noopener noreferrer"
          >对接文档</a
        >
      </template>
    </a-alert>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="16">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="搜索项">
              <a-input v-model:value="listQuery.title" placeholder="输入标题/ID搜索..." />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :icon="h(SearchOutlined)" @click="searchSubmit">
                搜索
              </a-button>
            </a-form-item>
            <a-form-item>
              <a-button
                v-permission="{ action: 'del_push_batch' }"
                type="primary"
                danger
                :disabled="selectedRowKeys.length === 0"
                @click="deleteSelect"
              >
                <template #icon>
                  <DeleteOutlined />
                </template>
                删除所选
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon>
                  <SyncOutlined />
                </template>
              </a-button>
            </a-tooltip>
            <a-button
              v-permission="{ action: 'push_server_add' }"
              type="primary"
              style="margin-left: 12px"
              @click="addNewData"
            >
              <template #icon>
                <PlusOutlined />
              </template>
              新增推送配置
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record._id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template #status="{ text: record }">
        <a-tag v-if="record == 1" color="green">启用</a-tag>
        <a-tag v-if="record == 0" color="red">关闭</a-tag>
      </template>
      <template #action="{ text: record }">
        <a v-permission="{ action: 'push_server_add' }" @click="push_server_edit(record)">
          <EditOutlined /> 编辑
        </a>
        <a-divider v-permission="{ action: 'push_server_webhook' }" type="vertical" />
        <a v-permission="{ action: 'push_server_webhook' }" @click="push_server_webhook(record)">
          Webhook
        </a>
        <a-divider v-permission="{ action: 'push_server_ext' }" type="vertical" />
        <a-dropdown>
          <a v-permission="{ action: 'push_server_ext' }" class="ant-dropdown-link">
            更多
            <DownOutlined />
          </a>
          <template #overlay>
            <a-menu>
              <a-menu-item v-permission="{ action: 'push_server_copy' }">
                <a @click="push_server_copy(record)"> <CopyOutlined /> 复制 </a>
              </a-menu-item>
              <a-menu-item v-permission="{ action: 'push_server_del' }" style="color: red">
                <a @click="push_server_delete(record)"> <DeleteOutlined /> 删除 </a>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </template>
    </a-table>
    <a-drawer
      width="50%"
      :title="drawerTitle"
      placement="right"
      :open="drawerShow"
      @close="
        () => {
          drawerShow = false
        }
      "
    >
      <template #extra>
        <a-button
          style="margin-right: 8px"
          @click="
            () => {
              drawerShow = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" @click="addServer">提交</a-button>
      </template>
      <a-form
        ref="formRef"
        :model="FormState"
        :rules="FormRule"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-tabs v-model:activeKey="activeKey" type="card">
          <a-tab-pane key="tab1" tab="推送设置">
            <a-form-item label="标题" has-feedback required name="title">
              <a-input v-model:value="FormState.title" placeholder="请输入标题" />
            </a-form-item>
            <a-form-item label="推送类别" has-feedback required name="type">
              <a-radio-group v-model:value="FormState.type">
                <a-radio key="app" value="app">APP推送消息</a-radio>
                <a-radio key="alert" value="alert">报警(业务)通知</a-radio>
                <a-radio key="inbox" value="inbox">站内信</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item v-if="FormState.type == 'app'" label="推送平台" name="platform">
              <a-radio-group v-model:value="FormState.platform">
                <a-radio key="getui" value="getui">个推(UniPush1.0)</a-radio>
                <a-radio key="umeng" value="umeng">友盟</a-radio>
                <a-radio key="jiguang" value="jiguang">极光</a-radio>
                <a-radio key="goeasy" value="goeasy">GoEasy</a-radio>
                <a-radio key="aliyun" value="aliyun" disabled>阿里</a-radio>
                <a-radio key="tencent" value="tencent" disabled>腾讯</a-radio>
                <!-- <a-radio key="huawei" value="huawei">华为</a-radio> -->
                <!-- <a-radio key="api_url" value="api_url">API</a-radio> -->
              </a-radio-group>
            </a-form-item>
            <a-form-item v-if="FormState.type == 'inbox'" label="推送平台" name="platform">
              <a-radio-group v-model:value="FormState.platform">
                <a-radio key="goeasy" value="goeasy">GoEasy</a-radio>
                <!-- <a-radio key="api_url" value="api_url">API</a-radio> -->
              </a-radio-group>
            </a-form-item>
            <a-form-item v-if="FormState.type == 'alert'" label="通知平台" name="platform_alert">
              <a-checkbox-group
                v-model:value="FormState.platform_alert"
                name="checkboxgroup"
                :options="alertPlatformOptions"
              />
            </a-form-item>
            <a-form-item label="屏蔽类型" name="shielding_type">
              <a-radio-group v-model:value="FormState.shielding_type" disabled>
                <a-radio key="none" value="none">夜间不屏蔽</a-radio>
                <a-radio key="night_pb" value="night_pb">夜间屏蔽</a-radio>
                <a-radio key="night_delay" value="night_delay">夜间屏蔽(次日早上9点发送)</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item label="语音提醒(限GoEasy)" name="voice_url">
              <a-input v-model:value="FormState.voice_url" placeholder="(可选)请输入mp3文件url" />
            </a-form-item>
            <a-form-item label="通知静默" name="silent">
              <a-tooltip placement="top">
                <template #title>
                  <span>如果配置了静默时间，则在静默时间的周期段内，相同通知最多通知一次</span>
                </template>
                <a-input
                  v-model:value="FormState.silent"
                  placeholder="(可选)请输入静默时长，单位：秒，输入0或不输入为不限制"
                  suffix="秒"
                />
              </a-tooltip>
            </a-form-item>
            <a-form-item label="配置状态" has-feedback required name="status">
              <a-radio-group v-model:value="FormState.status">
                <a-radio :key="1" :value="1">启用</a-radio>
                <a-radio :key="0" :value="0">关闭</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
              v-if="FormState.status === 0"
              label="关闭说明"
              has-feedback
              required
              name="close_msg"
            >
              <a-input v-model:value="FormState.close_msg" placeholder="请输入配置关闭说明" />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="FormState.platform == 'getui' && FormState.type == 'app'"
            key="tab2"
            tab="个推推送设置"
          >
            <a-form-item label="App Id" name="getui_app_id">
              <a-input v-model:value="FormState.getui_app_id" placeholder="请填写">
                <template #suffix>
                  <a href="https://dev.getui.com/dev/#/appManage" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="App Key" name="getui_app_key">
              <a-input v-model:value="FormState.getui_app_key" placeholder="请填写" :rows="2">
                <template #suffix>
                  <a href="https://dev.getui.com/dev/#/appManage" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="App Secret" name="getui_app_secret">
              <a-input v-model:value="FormState.getui_app_secret" placeholder="请填写" :rows="2">
                <template #suffix>
                  <a href="https://dev.getui.com/dev/#/appManage" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="Master Secret" name="getui_master_secret">
              <a-input v-model:value="FormState.getui_master_secret" placeholder="请填写" :rows="2">
                <template #suffix>
                  <a href="https://dev.getui.com/dev/#/appManage" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="FormState.platform == 'umeng' && FormState.type == 'app'"
            key="tab3"
            tab="友盟推送设置"
          >
            <a-form-item label="AppKey" name="umeng_app_key">
              <a-input v-model:value="FormState.umeng_app_key" placeholder="请填写">
                <template #suffix>
                  <a href="https://upush.umeng.com/apps/list" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="Umeng Message Secret" name="umeng_message_secret">
              <a-input
                v-model:value="FormState.umeng_message_secret"
                placeholder="请填写"
                :rows="2"
              >
                <template #suffix>
                  <a href="https://upush.umeng.com/apps/list" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="App Master Secret" name="umeng_master_secret">
              <a-input v-model:value="FormState.umeng_master_secret" placeholder="请填写" :rows="2">
                <template #suffix>
                  <a href="https://upush.umeng.com/apps/list" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="FormState.platform == 'jiguang' && FormState.type == 'app'"
            key="tab4"
            tab="极光推送设置"
          >
            <a-form-item label="AppKey" name="jiguang_app_key">
              <a-input v-model:value="FormState.jiguang_app_key" placeholder="请填写密钥ID">
                <template #suffix>
                  <a href="https://www.jiguang.cn/portal" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="Master Secret" name="jiguang_master_secret">
              <a-input
                v-model:value="FormState.jiguang_master_secret"
                placeholder="请填写访问密钥"
                :rows="2"
              >
                <template #suffix>
                  <a href="https://www.jiguang.cn/portal" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="FormState.type == 'alert' && inArray('phone', FormState.platform_alert) === true"
            key="tab5"
            tab="短信通知设置"
          >
            <a-form-item label="通知手机号" name="platform_alert_phone">
              <a-input
                v-model:value="FormState.platform_alert_phone"
                placeholder="请输入手机号，多个以英文,分割"
              />
            </a-form-item>
            <a-form-item label="推送配置" name="platform_alert_ss_id">
              <a-select v-model:value="FormState.platform_alert_ss_id" placeholder="请选择推送配置">
                <a-select-option v-for="d in allSmsServer" :key="d._id" :value="d._id">
                  {{ d.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="推送模板" name="platform_alert_st_id">
              <a-select v-model:value="FormState.platform_alert_st_id" placeholder="请选择推送模板">
                <a-select-option v-for="d in allSmsTpl" :key="d._id" :value="d._id">
                  {{ d.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="FormState.type == 'alert' && inArray('email', FormState.platform_alert) === true"
            key="tab6"
            tab="邮件通知设置"
          >
            <a-form-item label="通知邮箱" name="platform_alert_email">
              <a-input
                v-model:value="FormState.platform_alert_email"
                placeholder="请输入邮箱，多个以英文,分割"
              />
            </a-form-item>
            <a-form-item label="邮箱服务器" name="platform_alert_es_id">
              <a-select
                v-model:value="FormState.platform_alert_es_id"
                placeholder="请选择邮箱服务器"
              >
                <a-select-option v-for="d in allEmailServer" :key="d._id" :value="d._id">
                  {{ d.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="邮件模板" name="platform_alert_et_id">
              <a-select v-model:value="FormState.platform_alert_et_id" placeholder="请选择推送模板">
                <a-select-option v-for="d in allEmailTpl" :key="d._id" :value="d._id">
                  {{ d.title }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="
              FormState.type == 'alert' && inArray('weixin_work', FormState.platform_alert) === true
            "
            key="tab7"
            tab="企业微信机器人"
          >
            <a-form-item label="Webhook地址" name="platform_alert_weixin_work_webhook_url">
              <a-input
                v-model:value="FormState.platform_alert_weixin_work_webhook_url"
                placeholder="请输入Webhook地址"
              />
            </a-form-item>
            <a-form-item label="接收消息的成员ID" name="platform_alert_weixin_work_webhook_touser">
              <a-tooltip
                title="(选填)成员ID列表（多ID用‘|’分隔，最多支持1000个）。@all，则向全部成员发送"
              >
                <a-input
                  v-model:value="FormState.platform_alert_weixin_work_webhook_touser"
                  placeholder="(选填)成员ID列表（多ID用‘|’分隔，最多支持1000个）。@all，则向全部成员发送"
                >
                  <template #suffix>
                    <a
                      href="https://work.weixin.qq.com/wework_admin/frame#contacts"
                      target="_blank"
                    >
                      <a-tooltip
                        title="点击成员名，进行成员详情页，成员ID为“帐号”对应的内容，接口传入时本设定无效"
                      >
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </a>
                  </template>
                </a-input>
              </a-tooltip>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="
              FormState.type == 'alert' && inArray('weixin_app', FormState.platform_alert) === true
            "
            key="tab8"
            tab="企业微信应用消息"
          >
            <a-form-item label="应用来源" has-feedback required name="ww_apps_from">
              <a-radio-group v-model:value="FormState.ww_apps_from">
                <a-radio key="platform" value="platform">在[企业微信列表]中选择</a-radio>
                <a-radio key="alone" value="alone">单独设置</a-radio>
              </a-radio-group>
            </a-form-item>
            <a-form-item
              v-if="FormState.ww_apps_from == 'platform'"
              label="选择企业微信"
              name="ww_id"
            >
              <a-select
                v-model:value="FormState.ww_id"
                show-search
                placeholder="请选择(支持搜索)"
                :default-active-first-option="false"
                :show-arrow="true"
                :filter-option="false"
                :options="wwList"
                :fieldNames="{ value: '_id', label: 'title' }"
                @search="searchInput"
              >
                <template #notFoundContent>
                  <a-empty
                    image="https://img.alicdn.com/imgextra/i3/573804794/O1CN01IO097G1lHhdtoisyG_!!573804794.png"
                    :image-style="{
                      height: '90px'
                    }"
                  >
                    <template #description>
                      <view style="color: rgba(0, 0, 0, 0.88); padding-top: 20px">
                        暂无可选项，请先
                        <router-link :to="{ name: 'workList' }" target="_blank">添加</router-link>
                      </view>
                    </template>
                  </a-empty>
                </template>
              </a-select>
            </a-form-item>
            <a-form-item
              v-if="FormState.ww_apps_from == 'alone'"
              label="企业ID"
              name="platform_alert_weixin_app_corpid"
            >
              <a-input
                v-model:value="FormState.platform_alert_weixin_app_corpid"
                placeholder="请填写"
              >
                <template #suffix>
                  <a href="https://work.weixin.qq.com/wework_admin/frame#profile" target="_blank">
                    <a-tooltip title="点击跳转官网获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item
              v-if="FormState.ww_apps_from == 'alone'"
              label="AgentId"
              name="platform_alert_weixin_app_agentid"
            >
              <a-input
                v-model:value="FormState.platform_alert_weixin_app_agentid"
                placeholder="请填写"
              >
                <template #suffix>
                  <a href="https://work.weixin.qq.com/wework_admin/frame#apps" target="_blank">
                    <a-tooltip
                      title="每个应用都有唯一的agentid。在管理后台->“应用与小程序”->“应用”，点进某个应用，即可看到agentid。"
                    >
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item
              v-if="FormState.ww_apps_from == 'alone'"
              label="Secret"
              name="platform_alert_weixin_app_secret"
            >
              <a-input
                v-model:value="FormState.platform_alert_weixin_app_secret"
                placeholder="请填写"
              >
                <template #suffix>
                  <a href="https://work.weixin.qq.com/wework_admin/frame#apps" target="_blank">
                    <a-tooltip title="与AgentId获取位置相同">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="接收消息的成员手机号" name="platform_alert_weixin_app_touser">
              <a-tooltip
                title="(选填)成员手机号列表（多手机号用‘|’分隔，最多支持1000个）。@all，则向全部成员发送"
              >
                <a-input
                  v-model:value="FormState.platform_alert_weixin_app_touser"
                  placeholder="(选填)成员手机号列表（多手机号用‘|’分隔，最多支持1000个）。@all，则向全部成员发送"
                >
                  <template #suffix>
                    <a
                      href="https://work.weixin.qq.com/wework_admin/frame#contacts"
                      target="_blank"
                    >
                      <a-tooltip
                        title="点击成员名，进行成员详情页，成员ID为“帐号”对应的内容，接口传入时本设定无效"
                      >
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </a>
                  </template>
                </a-input>
              </a-tooltip>
            </a-form-item>
            <a-form-item label="接收消息的部门" name="platform_alert_weixin_app_toparty">
              <a-tooltip
                title="(选填)部门ID列表，多ID用‘|’分隔，最多支持100个。当touser为 @all 时忽略本参数"
              >
                <a-input
                  v-model:value="FormState.platform_alert_weixin_app_toparty"
                  placeholder="(选填)部门ID列表，多ID用‘|’分隔，最多支持100个。当touser为 @all 时忽略本参数"
                >
                  <template #suffix>
                    <a
                      href="https://work.weixin.qq.com/wework_admin/frame#contacts"
                      target="_blank"
                    >
                      <a-tooltip title="接口传入时本设定无效">
                        <QuestionCircleOutlined />
                      </a-tooltip>
                    </a>
                  </template>
                </a-input>
              </a-tooltip>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="
              FormState.type == 'alert' &&
              inArray('mp_weixin_template', FormState.platform_alert) === true
            "
            key="tab6"
            tab="公众号模板消息通知"
          >
            <a-form-item label="接收者openid" name="platform_alert_mp_weixin_template_openid">
              <a-input
                v-model:value="FormState.platform_alert_mp_weixin_template_openid"
                placeholder="(可选)请输入接收者openid，多个以英文,分割"
              />
            </a-form-item>
            <a-form-item label="公众号" name="platform_alert_mp_weixin_template_mwid">
              <a-select
                v-model:value="FormState.platform_alert_mp_weixin_template_mwid"
                placeholder="请选择公众号"
              >
                <a-select-option v-for="d in allMWServer" :key="d._id" :value="d._id">
                  {{ d.title }}
                </a-select-option>
              </a-select>
              <TypographyText type="secondary"
                >注：如下拉选项为空，请先通过【微信系】-【<router-link
                  :to="{ name: 'mpList' }"
                  target="_blank"
                  >公众号列表</router-link
                >】录入后再选择。</TypographyText
              >
            </a-form-item>
            <a-form-item label="模板id" name="platform_alert_mp_weixin_template_template_id">
              <a-input
                v-model:value="FormState.platform_alert_mp_weixin_template_template_id"
                placeholder="(可选)请输入模板id"
              />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="
              FormState.type == 'alert' && inArray('dingding', FormState.platform_alert) === true
            "
            key="tab9"
            tab="钉钉群机器人"
          >
            <a-form-item label="Webhook地址" name="platform_alert_dingding_webhook_url">
              <a-input
                v-model:value="FormState.platform_alert_dingding_webhook_url"
                placeholder="请输入Webhook地址"
              />
            </a-form-item>
            <a-form-item label="加签密钥" name="platform_alert_dingding_secret">
              <a-input
                v-model:value="FormState.platform_alert_dingding_secret"
                placeholder="请输入加签密钥"
              />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="
              FormState.type == 'alert' && inArray('feishuqun', FormState.platform_alert) === true
            "
            key="tab9"
            tab="飞书群机器人"
          >
            <a-form-item label="Webhook地址" name="platform_alert_feishuqun_webhook_url">
              <a-input
                v-model:value="FormState.platform_alert_feishuqun_webhook_url"
                placeholder="请输入Webhook地址"
              />
            </a-form-item>
            <a-form-item label="签名密钥" name="platform_alert_feishuqun_secret">
              <a-input
                v-model:value="FormState.platform_alert_feishuqun_secret"
                placeholder="请输入签名校验密钥"
              />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="
              (FormState.platform == 'goeasy' &&
                (FormState.type == 'app' || FormState.type == 'inbox')) ||
              (FormState.type == 'alert' && inArray('goeasy', FormState.platform_alert) === true)
            "
            key="tab10"
            tab="GoEasy"
          >
            <a-form-item label="Common key" name="platform_goeasy_common_key">
              <a-input v-model:value="FormState.platform_goeasy_common_key" placeholder="请填写">
                <template #suffix>
                  <a href="https://console.goeasy.io/#/application" target="_blank">
                    <a-tooltip title="进入“应用详情”获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="Subscribe key" name="platform_goeasy_subscribe_key">
              <a-input v-model:value="FormState.platform_goeasy_subscribe_key" placeholder="请填写">
                <template #suffix>
                  <a href="https://console.goeasy.io/#/application" target="_blank">
                    <a-tooltip title="进入“应用详情”获取">
                      <QuestionCircleOutlined />
                    </a-tooltip>
                  </a>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item label="Channel" name="platform_goeasy_channel">
              <a-input
                v-model:value="FormState.platform_goeasy_channel"
                placeholder="自定义Channel，仅限英文字母组合"
              />
            </a-form-item>
            <a-form-item label="地域" name="platform_goeasy_region">
              <a-select
                v-model:value="FormState.platform_goeasy_region"
                placeholder="请选择应用所属地域"
              >
                <a-select-option key="hangzhou" value="hangzhou"> 杭州 </a-select-option>
                <a-select-option key="singapore" value="singapore"> 新加坡 </a-select-option>
              </a-select>
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane
            v-if="
              FormState.type == 'alert' && inArray('api_url', FormState.platform_alert) === true
            "
            key="tab11"
            tab="API"
          >
            <a-form-item label="URL" name="platform_api_url">
              <a-input
                v-model:value="FormState.platform_api_url"
                placeholder="请填写完整接口地址，如：https://www.baidu.com/api"
              />
            </a-form-item>
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="密码">
              <a-input-search
                v-model:value="FormState.platform_api_url_password"
                placeholder="(可选)在请求的 X-Dev-Token HTTP头中发送，用于接收方验证请求合法性"
                enter-button="生成密码"
                @search="resetSecretYunxiao"
              />
            </a-form-item>
          </a-tab-pane>
          <a-tab-pane key="tab12" tab="对接密钥">
            <a-form-item label="SecretKey" name="server_secret">
              <a-input-search
                v-model:value="FormState.server_secret"
                placeholder="点击右侧“获取密钥”按钮进行获取"
                enter-button="获取密钥"
                @search="resetSecret"
              />
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-drawer>
    <a-modal
      v-model:open="visibleWebhook"
      title="Webhook"
      width="800px"
      okText="设置"
      @ok="handleOkWebhook"
    >
      <a-alert
        message="可将此Webhook地址添加到其他平台中，从而实现消息分发。当前仅支持接收json或form类型的数据。"
        type="info"
        show-icon
        style="margin-bottom: 30px"
      />
      <a-form ref="formRef">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="Webhook地址">
          <a-tooltip title="双击可复制 Webhook地址">
            <a-input-search
              v-model:value="FormState.hook_key"
              enter-button="重新生成"
              @dblclick="copyText(FormState.hook_key)"
              @search="reset_webhook"
            />
          </a-tooltip>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="对接至">
          <a-radio-group v-model:value="FormState.hook_platform">
            <a-radio key="yunxiao" value="yunxiao">云效</a-radio>
            <a-radio key="gitee" value="gitee">码云</a-radio>
            <a-radio key="git" value="git">Git</a-radio>
            <a-radio key="other" value="other">其他</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="FormState.hook_platform == 'yunxiao'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="Secret Token"
        >
          <a-input-search
            v-model:value="FormState.yunxiao_token"
            placeholder="(可选)为空则不校验"
            enter-button="生成密钥"
            @search="resetSecretYunxiao"
          />
        </a-form-item>
        <a-form-item
          v-if="FormState.hook_platform == 'gitee'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="WebHook 密码"
        >
          <a-input-search
            v-model:value="FormState.gitee_token"
            placeholder="(可选)为空则不校验"
            enter-button="生成密钥"
            @search="resetSecretGitee"
          />
        </a-form-item>
        <a-form-item
          v-if="FormState.hook_platform == 'git'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="Secret"
        >
          <a-input-search
            v-model:value="FormState.git_token"
            placeholder="(可选)为空则不校验"
            enter-button="生成密钥"
            @search="resetSecretGit"
          />
        </a-form-item>
        <a-form-item
          v-if="FormState.hook_platform == 'other'"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="Dev Token"
        >
          <a-input-search
            v-model:value="FormState.dev_token"
            placeholder="(可选)在请求的 X-Dev-Token HTTP头中发送，用于柠聚开发平台验证请求来源合法性"
            enter-button="生成密钥"
            @search="resetSecretDevToken"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref, h } from 'vue'
import {
  Row,
  Col,
  Modal,
  Divider,
  Image,
  Drawer,
  Switch,
  InputPassword,
  InputNumber,
  TypographyText,
  message,
  Tabs,
  TabPane
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  SearchOutlined,
  DeleteOutlined,
  DownOutlined,
  CopyOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons-vue'
import {
  delServerItem,
  getServerList,
  editServerInfo,
  delServerBatch,
  editHookInfo,
  resetPushWebhook
} from '@/api/push'
import { randomString, inArray, copyText } from '@/utils/common'
import { useRouter } from 'vue-router'
import { requestFailed, requestSuccess } from '@/utils/feedback'
import { getAllServerList, getAllTplList } from '@/api/sms'
import { getAllItem } from '@/api/mpweixin'
import {
  getAllServerList as getEmailServerList,
  getAllTplList as getAllEmailTpl
} from '@/api/email'
import { getAllWWList } from '@/api/wwork'

export default defineComponent({
  name: 'PushServer',
  components: {
    SyncOutlined,
    PlusOutlined,
    DownOutlined,
    TypographyText,
    SearchOutlined,
    CopyOutlined,
    EditOutlined,
    QuestionCircleOutlined,
    DeleteOutlined,
    [Tabs.name]: Tabs,
    [TabPane.name]: TabPane,
    [Modal.name]: Modal,
    [Row.name]: Row,
    [Drawer.name]: Drawer,
    [Switch.name]: Switch,
    [InputPassword.name]: InputPassword,
    [InputNumber.name]: InputNumber,
    [Col.name]: Col,
    [Image.name]: Image,
    [Divider.name]: Divider
  },
  setup() {
    const formRef = ref()
    const router = useRouter()
    const state = reactive<any>({
      loading: true,
      drawerShow: false,
      modalVisible: false,
      visibleWebhook: false,
      hook_url: '',
      hook_id: '',
      testEmail: '',
      drawerTitle: '推送配置详情',
      activeKey: 'tab1',
      dataList: [],
      wwList: [],
      allSmsServer: [],
      allSmsTpl: [],
      selectedRowKeys: [],
      selectedKeysPage: {},
      allEmailServer: [],
      allEmailTpl: [],
      allMWServer: [],
      alertPlatformOptions: [
        { label: '短信', value: 'phone' },
        { label: '邮件', value: 'email' },
        { label: '企业微信群机器人', value: 'weixin_work' },
        { label: '企业微信应用消息', value: 'weixin_app' },
        { label: '公众号模板消息', value: 'mp_weixin_template' },
        { label: '钉钉群机器人', value: 'dingding' },
        { label: '飞书群机器人', value: 'feishuqun' },
        { label: 'GoEasy', value: 'goeasy' },
        { label: 'API', value: 'api_url' }
      ],
      listQuery: {
        pageNo: 1,
        pageSize: 15,
        title: ''
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      pagination: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15,
        current: 1
      },
      columns: [
        {
          title: 'ID',
          dataIndex: '_id'
        },
        {
          title: '标题',
          dataIndex: 'title'
        },
        {
          title: '推送类别',
          dataIndex: 'type_title'
        },
        {
          title: '推送平台',
          dataIndex: 'platform_title'
        },
        {
          title: '配置状态',
          dataIndex: 'status',
          slots: { customRender: 'status' }
        },
        {
          title: '添加时间',
          dataIndex: 'create_time'
        },
        {
          title: '操作',
          width: '250px',
          slots: { customRender: 'action' }
        }
      ]
    })
    onMounted(() => {
      getDataList()
      getServerDataList()
      searchInput('')
    })
    function getServerDataList() {
      getAllServerList({}).then((res) => {
        state.allSmsServer = res
      })
      getAllTplList({}).then((res) => {
        state.allSmsTpl = res
      })
      getEmailServerList({}).then((res) => {
        state.allEmailServer = res
      })
      getAllEmailTpl({}).then((res) => {
        state.allEmailTpl = res
      })
      getAllItem({}).then((res) => {
        state.allMWServer = res
      })
    }

    function handleTableChange(e) {
      state.loading = true
      state.pagination.pageSize = e.pageSize
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      state.pagination.current = e.current
      getDataList()
    }
    function resetSecret() {
      FormState.server_secret = randomString(64)
    }
    function resetSecretYunxiao() {
      FormState.yunxiao_token = randomString(64)
    }
    function resetSecretGitee() {
      FormState.gitee_token = randomString(64)
    }
    function resetSecretGit() {
      FormState.git_token = randomString(64)
    }
    function resetSecretDevToken() {
      FormState.dev_token = randomString(64)
    }

    const FormState = reactive<any>({
      _id: '',
      title: '',
      platform: '',
      shielding_type: '',
      platform_alert: '',
      status: 1
    })
    const FormRule = {
      title: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
      status: [{ required: true, message: '请输选择配置状态', trigger: ['blur', 'change'] }]
    }

    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }

    function searchSubmit() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }
    function push_server_copy(itemData) {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerTitle = '复制推送配置'
      for (let item in itemData) {
        if (item != '_id' && item != 'server_secret') {
          let copyTips = item == 'title' ? ' - 复制' : ''
          if (item == 'platform_alert') {
            FormState[item] = itemData[item]
          } else {
            FormState[item] = itemData[item] + copyTips
          }
        }
      }
      console.log(FormState)
      state.drawerShow = true
    }
    function push_server_webhook(itemData) {
      if (itemData['hook_key'] == undefined || itemData['hook_key'] == '') {
        message.error('请先编辑推送配置以获取webhook地址')
        return false
      }
      state.hook_id = itemData['_id']
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in itemData) {
        FormState[item] = itemData[item]
      }
      state.visibleWebhook = true
    }

    function getDataList() {
      getServerList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }
    function push_server_edit(res) {
      state.drawerTitle = '编辑推送配置'
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in res) {
        FormState[item] = res[item]
      }
      state.drawerShow = true
    }
    function addNewData() {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerTitle = '新增推送配置'
      state.drawerShow = true
    }
    function reset_webhook() {
      Modal.confirm({
        title: '确认重新生成Webhook地址?',
        content: '确认后将重新生成webhook地址，原地址将立即失效',
        okType: 'danger',
        okText: '确认',
        onOk() {
          resetPushWebhook({ id: state.hook_id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              state.visibleWebhook = false
              getDataList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    function searchInput(v) {
      getWxWorkList(v)
    }
    function getWxWorkList(v) {
      getAllWWList({ platform: FormState.platform, title: v }).then((res) => {
        state.wwList = res
      })
    }
    function push_server_delete(data) {
      Modal.confirm({
        title: '确认永久删除本配置?',
        content: '【' + data._id + '】',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delServerItem({ id: data._id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              getDataList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    const addServer = () => {
      formRef.value
        .validate()
        .then(() => {
          editServerInfo(FormState).then((res) => {
            if (res.code === 200) {
              requestSuccess(res)
              formRef.value.resetFields()
              state.loading = true
              state.drawerShow = false
              reloadList()
            } else {
              requestFailed(res)
            }
          })
        })
        .catch(() => {
          return false
        })
    }
    const handleOkWebhook = () => {
      editHookInfo(FormState).then((res) => {
        if (res.code === 200) {
          requestSuccess(res)
          state.loading = true
          state.visibleWebhook = false
          getDataList()
        } else {
          requestFailed(res)
        }
      })
    }
    function deleteSelect() {
      Modal.confirm({
        title: '确认批量删除所选内容?',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delServerBatch({ ids: state.selectedRowKeys })
            .then((res) => {
              if (res.code === 200) {
                state.loading = true
                getDataList()
                requestSuccess(res)
              } else {
                requestFailed(res)
              }
            })
            .finally(() => {
              state.selectedRowKeys = []
            })
        }
      })
    }
    const onSelectChange = (selectedRowKeys) => {
      state.selectedKeysPage[state.listQuery.pageNo] = selectedRowKeys
      let nowList: any[] = []
      for (const key in state.selectedKeysPage) {
        nowList = nowList.concat(state.selectedKeysPage[key])
      }
      const uniqueList = [...new Set(nowList)]
      state.selectedRowKeys = uniqueList
    }
    return {
      ...toRefs(state),
      handleTableChange,
      deleteSelect,
      onSelectChange,
      reloadList,
      handleOkWebhook,
      resetSecret,
      resetSecretGitee,
      resetSecretDevToken,
      resetSecretGit,
      resetSecretYunxiao,
      searchSubmit,
      push_server_delete,
      reset_webhook,
      formRef,
      addServer,
      FormState,
      h,
      FormRule,
      addNewData,
      copyText,
      router,
      inArray,
      searchInput,
      push_server_edit,
      push_server_webhook,
      push_server_copy,
      getDataList
    }
  }
})
</script>

<style scoped></style>
